package com.bytz.modules.cms.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.modules.cms.order.constant.OrderPayConstants;
import com.bytz.modules.cms.order.entity.OrderPickUpDetail;
import com.bytz.modules.cms.order.mapper.OrderPickUpDetailMapper;
import com.bytz.modules.cms.order.service.IOrderPickUpDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 莱宝CMS—订单管理-订单交易提货明细表 服务实现类
 * </p>
 *
 * @author KyleWang
 * @since 2022-10-10
 */
@Service
public class OrderPickUpDetailServiceImpl extends ServiceImpl<OrderPickUpDetailMapper, OrderPickUpDetail> implements IOrderPickUpDetailService {

    @Override
    public List<OrderPickUpDetail> getByOrderId(String orderId) {

        if (StringUtils.isBlank(orderId)) {
            return new ArrayList<>();
        }

        return lambdaQuery().eq(OrderPickUpDetail::getOrderId, orderId).list();
    }

    @Override
    public List<OrderPickUpDetail> getByOrderPayId(String orderPayId) {

        if (StringUtils.isBlank(orderPayId)) {
            return new ArrayList<>();
        }

        return lambdaQuery().eq(OrderPickUpDetail::getOrderPayId, orderPayId).list();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void directSubmitBalancePay(List<OrderPickUpDetail> pickUpDetails, String orderPayId) {
        savePickupDetails(pickUpDetails, orderPayId, OrderPayConstants.PayStatus.DONE);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void savePickupDetails(List<OrderPickUpDetail> pickUpDetails, String orderPayId) {
        savePickupDetails(pickUpDetails, orderPayId, OrderPayConstants.PayStatus.PAYING);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitBalancePay(String orderPayId) {
        updatePickupDetailsByPayId(orderPayId, OrderPayConstants.PayStatus.DONE);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rollbackBalancePay(String orderPayId) {
        updatePickupDetailsByPayId(orderPayId, OrderPayConstants.PayStatus.FAILED);
    }

    private void savePickupDetails(List<OrderPickUpDetail> pickUpDetails, String orderPayId, String status) {
        for (OrderPickUpDetail pickUpDetail : pickUpDetails) {
            pickUpDetail.setOrderPayId(orderPayId);
            pickUpDetail.setStatus(status);
        }

        saveBatch(pickUpDetails);
    }

    private void updatePickupDetailsByPayId(String orderPayId, String status) {
        lambdaUpdate().set(OrderPickUpDetail::getStatus, status)
                .eq(OrderPickUpDetail::getOrderPayId, orderPayId)
                .update();
    }
}
